/**
 * modalInfoProp：接口返回的提示触发弹框，比如未给资源池分配配额,或者订单返回配额不足信息(JSONString)
 * mode：弹框方式 tip（无表格弹框），''或不设置（正常表格弹框）
 * type: 类型 quota（配额弹框），resource（资源弹框）,涉及到表头显示
 * modalColumnsProp：定制化表格列
 * handleOk：确认弹框
 * okText：确认按钮文字
 * warningText：默认defaultWarningText，可指定表格上部或tip的提示文字
 */
import React, { useState, useEffect, useImperativeHandle } from "react";
import { HcpTipModal, HcpTable } from '@/components'
import hcpUtils from "@/utils/hcpUtils";
import request from "@/utils/request";
import { Button, Modal, Table, Form } from "antd";

const HcpCreateRsQuotaErrorModal = ({ cRef, mode, modalInfoProp, type = 'quota',
  modalColumnsProp, handleOk, okText = "知道了", warningText }) => {
  const defaultWarningText = `您所选择的规格配额不足，请增加配额或选择在其他项目下进行创建`
  const columns = [
    {
      title: '名称',
      align: "center",
      dataIndex: 'name',
      render: (text, record) => { return `${text}(${record.unit})`; }
    },
    {
      title: `剩余${type === 'resource' ? '资源' : '配额'}`,
      align: "center",
      dataIndex: 'surplusQuota'
    },
    {
      title: '当前申请',
      align: "center",
      dataIndex: 'prtyValue'
    }
  ];
  const [thisMode, setThisMode] = useState('')
  const [modalWarningText, setModalWarningText] = useState(defaultWarningText)
  const [quotaShortTipShow, setQuotaShortTipShow] = useState(false)
  const [modalInfo, setModalInfo] = useState([]); // 提示框表格信息
  const [modalColumns, setModalColumns] = useState(modalColumnsProp || columns); // 表格列
  const [modalVisible, setModalVisible] = useState(false); // 提示框展示状态

  useEffect(() => {
    setThisMode(mode)
  }, [mode])
  useEffect(() => {
    if (type && !modalColumnsProp) {
      setModalColumns(columns)
    }
  }, [type])
  useEffect(() => {
    if (modalColumnsProp?.length) {
      setModalColumns(modalColumnsProp)
    }
  }, [modalColumnsProp])
  useEffect(() => {
    if (warningText) {
      setModalWarningText(warningText)
    }
  }, [warningText])
  // 动态弹框
  useEffect(() => {
    if (modalInfo.length > 0) {
      setModalVisible(true);
    }
  }, [modalInfo]);
  useEffect(() => {
    if (modalInfoProp?.length > 0) {
      setModalVisible(true);
      setModalInfo(getModalInfos(modalInfoProp));
    }
  }, [modalInfoProp]);
  useImperativeHandle(cRef, () => ({
    emitQuotaCheck: async (quotaCheckApi, quotaCheckData) => {
      setQuotaShortTipShow(false)
      if (quotaCheckApi) {
        const res = await request({
          ...quotaCheckApi,
          data: quotaCheckData
        });
        if (res && res.code === 9000) {
          setModalWarningText(warningText || defaultWarningText)
          setModalInfo(getModalInfos(res.msg));
          return false
        } else if (res && res.code === 9001) {
          setQuotaShortTipShow(true)
          setModalWarningText(defaultWarningText)
          setModalVisible(true);
        } else if (res && res.code === 200) {
          setModalInfo([]);
          return res
        }
      } else {
        return false
      }
    },
    emitGpQuotaCheck: async (quotaCheckApi, quotaCheckData) => {
      setQuotaShortTipShow(false)
      if (quotaCheckApi) {
        const res = await request({
          ...quotaCheckApi,
          data: quotaCheckData
        });
        if (res && res.code === 9000) {
          setModalInfo(getModalInfos(res.msg));
          return res
        } else if (res && res.code === 200) {
          setModalInfo([]);
          return res
        }
      } else {
        return false
      }
    }
  }));
  const getModalInfos = (message) => {
    if (hcpUtils.isJSON(message)) {
      if (!mode) setThisMode('')
      const msg = JSON.parse(message);
      let msgList = msg;
      if (!Array.isArray(msg)) {
        msgList = [msg];
      }
      const finalList = msgList.map((item, index) => {
        return { ...item, key: index, prtyValue: item.need };
      });
      return finalList
    } else {
      if (!mode) {
        setThisMode('tip');
        setModalWarningText(message);
      }
      return []
    }
  }
  return <>
    {
      thisMode === 'tip' || quotaShortTipShow ? <HcpTipModal
        title="提示"
        maskClosable={false}
        visible={modalVisible}
        onFinish={() => { setModalVisible(false); if (handleOk) handleOk(); }}
        okText='知道了'
        cancelText=''
        onCancel={() => { setModalVisible(false); if (handleOk) handleOk(); }}
        content={
          <>
            <div className="main-content">
              <span className="iconfont iconfont-yellow icon-confirm-warning" />
              <span className="main-content-info">{modalWarningText}</span>
            </div>
            <div className="sub-content gray"></div>
          </>
        }
      /> : <Modal
        title="提示"
        maskClosable={false}
        visible={modalVisible}
        className={modalColumns.length > 3 ? 'hcp-modal-md' : ''}
        footer={null}
        onCancel={() => { setModalVisible(false); if (handleOk) handleOk(); }}
        destroyOnClose
      >
        <p><span className="iconfont iconfont-sm iconfont-yellow icon-confirm-warning" />
          <span style={{ fontSize: 13 }}>{modalWarningText}</span></p>
        <HcpTable hideSetting dataSource={modalInfo} columns={modalColumns} scroll={{}}
          rowKey="name" pagination={false} />
        <div style={{ textAlign: 'right', marginTop: '20px' }}><Button type="primary"
          onClick={() => { setModalVisible(false); if (handleOk) handleOk() }}>{okText}</Button></div>
      </Modal>
    }

  </>
};
export default HcpCreateRsQuotaErrorModal;